package com.handpay.zztong.hp.paymentbill.activity;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.DateUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.adapter.QueryBillsAdapter;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.Bill;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.paymentbill.model.bill.QueryTransactionBillsBean;
import com.handpay.zztong.hp.paymentbill.model.bill.QueryTransactionBillsModel;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.paymentbill.widget.CalendarDialogView;
import com.handpay.zztong.hp.paymentbill.widget.CalendarView;
import com.handpay.zztong.hp.webpay.model.AccountTransfer;
import com.handpay.zztong.hp.ui.ZZTShowDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

/**
 * 交易查询
 *
 * @author ppliu
 */
public class QueryBillsActivity extends ZZTongActivity implements View.OnClickListener, CalendarView.OnItemClickListener {
    final private int QUERY_BILLS_REQ_CODE = 1;
    private boolean isDatePickerDialog4StartDate = false;
    private ZZTShowDialog<CalendarDialogView> mCalendarDialog;
    // 起始日期控件
    private TextView startDateShowTextView;
    // 结束日期控件
    private TextView endDateShowTextView;
    // 页码信息
    private TextView tvPageInfo;
    // 分页按钮
    private Button btnLast;
    private Button btnNext;
    // 起始日期
    private Date startDate;
    // 结束日期
    private Date endDate;
    // 交易账单列表
    private List<Bill> bills;
    // 总金额,总笔数
    private TextView tvAmounts, tvItems;

    private boolean isQueryBills = false;
    /**
     * 交易账单listview
     */
    private ListView queryBillsListView;
    private LinearLayout queryBillsListViewFooterView;
    private static final String[] transStatusType = {"全部", "交易成功", "交易失败", "交易处理中"};
    private static final String[] revokeStatusType = {"全部", "已撤销", "撤销中", "撤销失败"};
    private static final String[] transModeType = {"全部", "刷卡支付", "支付宝支付", "微信支付"};
    private String transStatus;// 交易状态
    private String revokeStatus;// 撤销状态
    private String transMode = "1";// 交易方式 默认刷卡收款
    private String transNo;// 交易流水号
    private int pageNo = 1;
    private int totalPages = -1;
    private EditText et_transSN = null;
    /**
     * 交易账单listview adapter
     */
    private QueryBillsAdapter queryBillsAdapter;
    private QueryBillsActivity context;
    public static final String billvalue = "bill";
    //	private boolean isQueryBills = false;
    private int curr_position = 0;
    private LinearLayout ll_amount_pages;

    @Override
    protected boolean isShownTopBar() {
        return true;
    }

    @Override
    public ActionBar getActivityActionBar() {
//        if (ClientEngine.CHANNEL.equals("FASTBILL")) {
        return new ActionBar(this.getString(R.string.credit_card), true);
//        } else {
//            TextView tv = new TextView(this);
//            tv.setText("申诉记录");
//            tv.setTextSize(14);
//            tv.setTextColor(this.getResources().getColor(R.color.backgournd_white_color));
//            tv.setPadding(0, 0, 30, 0);
//            tv.setOnClickListener(CommonUtils.createNoQuickResponseViewListener(ZZTConstant.NO_RESPONSE_CLICK_TIME, new View.OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent(QueryBillsActivity.this, QueryAppeals.class);
//                    startActivity(intent);
//                }
//            }));
//            return new ActionBar(this.getString(R.string.credit_card), true, tv);
//        }
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_querybills);
        super.onCreate(savedInstanceState);

        context = this;
        mCalendarDialog = new ZZTShowDialog<>(this, new CalendarDialogView(this), R.style.dialog);
        mCalendarDialog.getContentView().getCalendar().setOnItemClickListener(this);

        this.queryBillsListView = (ListView) findViewById(R.id.queryBillsListView);
        this.queryBillsListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                curr_position = arg2 - 1;
                Bill bill = bills.get(arg2 - 1);
                HPLog.d(HPLog.SSX_TAG, bill.toString());
                Intent intent = new Intent();
                if (Bill.STATUS_SUCCESS == bill.getStatus()) {
//                    if (!TextUtils.isEmpty(bill.getDetailUrl())) {//只有保存了签名的时候才隐藏状态 杀死进程没有保存状态
//                        intent.putExtra("isHideState", true);//交易成功的時候已经保存了交易状态，订单流水就不需要显示交易状态 不然状态会重复
//                    }
                    intent.setClass(context, TransResultSuccessActivity.class);
                    intent.putExtra(billvalue, bill);
                    intent.putExtra(ACTION, Action_QueryBills);
                    context.startActivityForResult(intent, QUERY_BILLS_REQ_CODE);
                } else if (Bill.STATUS_FAILED == bill.getStatus() || Bill.STATUS_NOT_PAY == bill.getStatus() || Bill.STATUS_CLOSED == bill.getStatus()) {
                    intent.setClass(context, TransResultFailureActivity.class);
                    intent.putExtra(billvalue, bill);
                    intent.putExtra(ACTION, Action_QueryBills);
                    context.startActivity(intent);
                } else if (Bill.STATUS_PROCESSING == bill.getStatus()) {
                    intent.setClass(context, TransResultFailureActivity.class);
                    intent.putExtra(billvalue, bill);
                    intent.putExtra(ACTION, Action_QueryBills);
                    context.startActivity(intent);
                }
            }
        });

        LayoutInflater inflater = LayoutInflater.from(this);
        this.queryBillsListViewFooterView = (LinearLayout) inflater.inflate(R.layout.layout_more_item, null);
        this.tvPageInfo = (TextView) queryBillsListViewFooterView.findViewById(R.id.tvPageInfo);
        Button btnIndex = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnIndex);
        Button btnEnd = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnEnd);
        this.btnLast = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnLast);
        this.btnNext = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnNext);
        btnIndex.setOnClickListener(this);
        btnEnd.setOnClickListener(this);
        this.btnLast.setOnClickListener(this);
        this.btnNext.setOnClickListener(this);

        this.queryBillsListView.addFooterView(this.queryBillsListViewFooterView);
        LinearLayout headerView = (LinearLayout) inflater.inflate(R.layout.layout_querybills_header, null);
        //隐藏流水单号
        headerView.findViewById(R.id.revoke_status).setVisibility(View.GONE);
        headerView.findViewById(R.id.queryButton).setOnClickListener(this);

        headerView.findViewById(R.id.startDateRow).setOnClickListener(this);

        headerView.findViewById(R.id.endDateRow).setOnClickListener(this);
        Spinner spinnerTransStatus = (Spinner) headerView.findViewById(R.id.transStatus_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.myspinnerdropdown, transStatusType);
        spinnerTransStatus.setAdapter(adapter);
        // 添加事件Spinner事件监听
        spinnerTransStatus.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view;
                tv.setTextSize(16.0f);
                // 0 成功 1 失败 2处理中 null为不传
                if (position == 0) {
                    transStatus = null;// 查询全部
                } else if (position == 1) {
                    transStatus = "1";// 1表示成功，
                } else if (position == 2) {
                    transStatus = "0";// 0表示失败
                } else if (position == 3) {
                    transStatus = "2";// 2交易处理中
                } else if (position == 4) {
                    transStatus = "3";
                } else if (position == 5) {
                    transStatus = "4";
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        Spinner spinnerRevokeStatus = (Spinner) headerView.findViewById(R.id.revokeStatus_spinner);
        ArrayAdapter<String> revokeAdapter = new ArrayAdapter<>(this, R.layout.myspinnerdropdown, revokeStatusType);
        spinnerRevokeStatus.setAdapter(revokeAdapter);
        spinnerRevokeStatus.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view;
                tv.setTextSize(16.0f);
                HPLog.i("queryBills========", "position:" + position);
                // 1 已经撤销 2 撤销中 3撤销失败 null全部
                if (position == 0) {
                    revokeStatus = null;// null 全部
                } else if (position == 1) {
                    revokeStatus = "1";// 1表示成功，
                } else if (position == 2) {
                    revokeStatus = "2";// 3表示撤销中，
                } else if (position == 3) {
                    revokeStatus = "3";// 2撤销失败
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });

//        Spinner spinnerTransMode = (Spinner) headerView.findViewById(R.id.transMode_spinner);
//        ArrayAdapter<String> modeAdapter = new ArrayAdapter<>(this, R.layout.myspinnerdropdown, transModeType);
//        spinnerTransMode.setAdapter(modeAdapter);
//        spinnerTransMode.setOnItemSelectedListener(new OnItemSelectedListener() {
//
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                TextView tv = (TextView) view;
//                tv.setTextSize(16.0f);
//                HPLog.e("queryBills========", "position:" + position);
//                if (position == 0) {
//                    transMode = null;// 00 全部 不传该参数表示查询全部
//                } else if (position == 1) {
//                    transMode = "1";// 01刷卡读卡，POSPAY 刷卡支付
//                } else if (position == 2) {
//                    transMode = "2";// 02支付宝支付，ALIPAY支付宝支付
//                } else if (position == 3) {
//                    transMode = "3";// 03微信支付 WECHATPAY微信支付
//                }
//
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> arg0) {
//            }
//        });

        Date today = DateUtils.formatStringToDate(DateUtils.formatDateToString(new Date(), "yyyyMMdd"), "yyyyMMdd");
        this.et_transSN = (EditText) headerView.findViewById(R.id.et_transSN);
        this.startDateShowTextView = (TextView) headerView.findViewById(R.id.startDateShowTextView);
        this.endDateShowTextView = (TextView) headerView.findViewById(R.id.endDateShowTextView);
        this.startDate = today;
        this.startDateShowTextView.setText(DateUtils.formatDateToString(startDate, "yyyy-MM-dd"));

        this.endDate = new Date(today.getTime() + (24 * 60 * 60 * 1000) - 1);
        this.endDateShowTextView.setText(DateUtils.formatDateToString(today, "yyyy-MM-dd"));

        this.queryBillsListView.addHeaderView(headerView);
        this.queryBillsListView.setAdapter(null);
        ll_amount_pages = (LinearLayout) headerView.findViewById(R.id.ll_amount_pages);
        ll_amount_pages.setVisibility(View.GONE);
        tvAmounts = (TextView) headerView.findViewById(R.id.tvAmounts);
        tvAmounts.setText("");
        tvItems = (TextView) headerView.findViewById(R.id.tvItems);
        tvItems.setText("");
    }

    /**
     * 发送交易查询请求
     */
    private void sendQueryRequest(int page) {
        /*
         * if (!checkVPOS(this, VPOSActivity.Action_QueryBills)) { return; }
		 */
        Hashtable<String, String> params = new Hashtable<>();
        params.put("startTime", DateUtils.formatDateToString(this.startDate, "yyyyMMddHHmmss"));
        params.put("endTime", DateUtils.formatDateToString(this.endDate, "yyyyMMddHHmmss"));
        params.put("pageSize", "5");
        params.put("pageNo", page + "");// account
        // params.put(BaseProtocolKey.ACCOUNT,
        // SecureManager.getInstance().des(AccountUtils.getAccountName(), 1,
        // null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put("appCode", BaseProtocolKey.APPCODE_TRANSFER); // 应用代码 ASCII字符
        if (!TextUtils.isEmpty(transStatus)) {
            params.put("status", transStatus); // 查询交易状态
        }
        if (!TextUtils.isEmpty(revokeStatus)) {
            params.put("revokeStatus", revokeStatus); // 撤销条件
        }
        if (!TextUtils.isEmpty(transMode)) {
            params.put("tradeType", transMode); // 交易类型
        }
        if (!TextUtils.isEmpty(transNo)) {
            //解决输入流水单号超出Integer的最大值的情况
            if (Double.valueOf(transNo) >= Integer.MAX_VALUE) {
                this.showAlertDialog(this, R.string.tip, R.string.hint_transno);
                return;
            }
            params.put("transSN", transNo); // 交易流水

        }
//        doJsonPost(this, Do_NewQueryAccountBills, QueryTransactionBillsBean.class, params);
        new QueryTransactionBillsModel().doQueryAccountBillsPost(this, params, new BusinessEngineListener<QueryTransactionBillsBean>() {
            @Override
            public void callbackBusinessResponse(QueryTransactionBillsBean bean) {
                Double amounts = Double.valueOf(bean.getAmounts());

                ll_amount_pages.setVisibility(View.VISIBLE);
                if (amounts == null || amounts.intValue() <= 0) {
                    tvAmounts.setText("");
                } else {
                    tvAmounts.setText(Html.fromHtml(getString(R.string.infoamounts, getResources().getColor(R.color.light_blue), CommonUtils.formatMoney(amounts / 100))));
                }
                // 总笔数
                // Double items = (Double) luaTable.rawget("items");
                Double items = Double.valueOf(bean.getItems());
                if (items == null || items.intValue() <= 0) {
                    tvItems.setText("");
                } else {
                    tvItems.setText(Html.fromHtml(getString(R.string.infoitems, getResources().getColor(R.color.light_blue), items.intValue())));
                }
                // totalPages = (Double) luaTable.rawget("totalPages");
                totalPages = CommonUtils.objectToInt(bean.getTotalPages());
//            LuaTable list = (LuaTable) luaTable.rawget("list"); bean.
                List<AccountTransfer> list = bean.getList();
                // this.bills = new ArrayList<Bill>();
                // 测试数据
                // this.bills.add(CommonUtils.simulationBillData());
                if (list != null) {
                    bills = new ArrayList<>();
                    queryBillsAdapter = new QueryBillsAdapter(QueryBillsActivity.this, bills);
                    queryBillsListView.setAdapter(queryBillsAdapter);
                    for (AccountTransfer billData : list) {
                        Bill bill = CommonUtils.generateBill(billData, null);
                        bills.add(bill);
                    }
                }

                if (list == null || list.size() == 0) {
                    showAlertDialog(QueryBillsActivity.this, R.string.tip, R.string.no_data);
                    queryBillsAdapter = new QueryBillsAdapter(QueryBillsActivity.this, new ArrayList<Bill>());
                    queryBillsListView.setAdapter(queryBillsAdapter);
                    if (pageNo < 2) {
                        queryBillsListViewFooterView.setVisibility(View.GONE);
                    }
                    return ;
                }
                queryBillsListView.setSelection(curr_position);
                tvPageInfo.setText("第" + pageNo + "页" + "  共" + totalPages + "页");
                queryBillsSuccessHandler.sendMessage(queryBillsSuccessHandler.obtainMessage());
                queryBillsListViewFooterView.setVisibility(View.VISIBLE);
                if (pageNo == 1) {
                    btnLast.setEnabled(false);
                } else {
                    btnLast.setEnabled(true);
                }
                if (pageNo == totalPages) {
                    btnNext.setEnabled(false);
                } else {
                    btnNext.setEnabled(true);
                }
            }

        });
    }

    // 成功获取数据handler
    private Handler queryBillsSuccessHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 通知adapter
            QueryBillsActivity.this.queryBillsAdapter.notifyDataSetChanged();
            QueryBillsActivity.this.queryBillsListView.setVisibility(View.VISIBLE);
            QueryBillsActivity.this.closeProgressDialog();
        }
    };



    @Override
    public void onClick(View v) {
        super.onClick(v);
        int i = v.getId();
        if (i == R.id.startDateRow) {
            this.isDatePickerDialog4StartDate = true;
            mCalendarDialog.getContentView().setCalendarData(startDate);
            mCalendarDialog.show();
        } else if (i == R.id.endDateRow) {
            this.isDatePickerDialog4StartDate = false;
            mCalendarDialog.getContentView().setCalendarData(endDate);
            mCalendarDialog.show();
        } else if (i == R.id.queryButton || i == R.id.btnIndex) {
            pageNo = 1;
            isQueryBills = true;
            if (DateUtils.isOkDate(this, startDate, endDate)) {
                //隐藏键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et_transSN.getWindowToken(), 0);
                if (DateUtils.changequerystate(startDate, endDate)) {
                    // 查询

                    doNet();
                } else {
                    this.showAlertDialog(this, getString(R.string.tip), getString(R.string.txselectoutoftime), true, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                }
            }
        } else if (i == R.id.btnNext) {
            pageNo++;
            if (DateUtils.isOkDate(this, startDate, endDate)) {
                if (DateUtils.changequerystate(startDate, endDate)) {
                    doNet();
                } else {
                    this.showAlertDialog(this, getString(R.string.tip), getString(R.string.txselectoutoftime), true, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                }
            }
        } else if (i == R.id.btnLast) {
            pageNo--;
            doNet();

        } else if (i == R.id.btnEnd) {
            pageNo = totalPages;
            doNet();

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == QUERY_BILLS_REQ_CODE) {
            if (isQueryBills) {
                sendQueryRequest(pageNo);
            }
        }
    }

    private void doNet() {
        if (this.startDate == null) {
            this.showAlertDialog(this, R.string.tip, R.string.select_start_date_tip);
            return;
        }
        if (this.endDate == null) {
            this.showAlertDialog(this, R.string.tip, R.string.select_end_date_tip);
            return;
        }
        if (startDate.after(endDate)) {
//            this.showAlertDialog(this, R.string.tip, R.string.select_date_tip);
            this.showAlertDialog(this, R.string.tip, R.string.select_trans_no_tip);

            return;
        }
        transNo = et_transSN.getEditableText().toString();
        if (!TextUtils.isEmpty(transNo) && transNo.length() < 8) {
            this.showAlertDialog(this, R.string.tip, R.string.select_trans_no_tip);
            return;
        }
        sendQueryRequest(pageNo);
    }

    @Override
    public void OnItemClick(Date selectedStartDate, Date selectedEndDate, Date downDate) {
        mCalendarDialog.dismiss();
        if (this.isDatePickerDialog4StartDate) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(downDate);
            this.startDate = calendar.getTime();
            this.startDateShowTextView.setText(DateUtils.formatDateToString(startDate, "yyyy-MM-dd"));
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(downDate);
            this.endDate = new Date(calendar.getTimeInMillis() + (24 * 60 * 60 * 1000) - 1);
            this.endDateShowTextView.setText(DateUtils.formatDateToString(endDate, "yyyy-MM-dd"));
        }
    }
}
